from numpy import *

# 载入数据集
def loadDataSet(fileName):      
    dataMat = []                
    fr = open(fileName)
    for line in fr.readlines():
        curLine = line.strip().split('\t')
        fltLine = list(map(float,curLine)) #map all elements to float()
        dataMat.append(fltLine)
    return dataMat

# 计算两个向量之间的欧式距离
def distEclud(vecA, vecB):
    return sqrt(sum(power(vecA - vecB, 2))) #la.norm(vecA-vecB)

# 为给定数据集构建一个包含k个随机质心的集合
def randCent(dataSet, k):
    n = shape(dataSet)[1] # 获取数据集的维度数
    centroids = mat(zeros((k,n))) # 初始化质心矩阵
    for j in range(n):#create random cluster centers, within bounds of each dimension
        minJ = min(dataSet[:,j]) 
        rangeJ = float(max(dataSet[:,j]) - minJ)
        centroids[:,j] = mat(minJ + rangeJ * random.rand(k,1))
    return centroids

# K-均值聚类算法，输出质心矩阵centroids和簇分配结果矩阵clusterAssment    
def kMeans(dataSet, k, distMeas=distEclud, createCent=randCent):
    m = shape(dataSet)[0] # 获取样本数m
    clusterAssment = mat(zeros((m,2)))  #  初始化簇分配结果矩阵，第一列记录簇索引值，第二列存储误差
    centroids = createCent(dataSet, k)
    clusterChanged = True
    while clusterChanged:
        clusterChanged = False
        for i in range(m): #for each data point assign it to the closest centroid
            minDist = inf; minIndex = -1
            for j in range(k): # 寻找最近的质心
                distJI = distMeas(centroids[j,:],dataSet[i,:])
                if distJI < minDist:
                    minDist = distJI; minIndex = j
            if clusterAssment[i,0] != minIndex: clusterChanged = True
            clusterAssment[i,:] = minIndex,minDist**2 
        print ("更新聚类质心：",centroids)
        for cent in range(k): # 更新质心的位置
            ptsInClust = dataSet[nonzero(clusterAssment[:,0].A==cent)[0]]#get all the point in this cluster
            centroids[cent,:] = mean(ptsInClust, axis=0) # axis=0表示，沿列方向求均值 
    return centroids, clusterAssment

# 绘制K-均值聚类结果示意图
def plotKMeans(dataSet,clusterAssment,centroids):
    import matplotlib
    import matplotlib.pyplot as plt
    plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus']=False    # 用来正常显示负号
    fig = plt.figure()
    ax = fig.add_subplot(111)
    xcord1 = []; ycord1 = []; xcord2 = []; ycord2 = []
    xcord3 = []; ycord3 = []; xcord4 = []; ycord4 = []
    xCentroids = []; yCentroids = []; 
    m = shape(dataSet)[0] # 获取样本数m
    for i in range(m):
        if (clusterAssment[i,0] == 1):
           xcord1.append(dataSet[i,0])
           ycord1.append(dataSet[i,1])
        elif (clusterAssment[i,0] == 2):
            xcord2.append(dataSet[i,0])
            ycord2.append(dataSet[i,1])
        elif (clusterAssment[i,0] == 3):
            xcord3.append(dataSet[i,0])
            ycord3.append(dataSet[i,1])
        else:
            xcord4.append(dataSet[i,0])
            ycord4.append(dataSet[i,1])
    for j in range(len(centroids)):
        xCentroids.append(centroids[j,0])
        yCentroids.append(centroids[j,1])
    ax.scatter(xcord1,ycord1, marker='^', s=90, c='red')
    ax.scatter(xcord2,ycord2, marker='d', s=90, c='lightskyblue')
    ax.scatter(xcord3,ycord3, marker='o', s=90, c='lightcoral')
    ax.scatter(xcord4,ycord4, marker='s', s=90, c='yellowgreen')
    ax.scatter(xCentroids,yCentroids, marker='+', s=100, c='k')
    plt.title('K-均值聚类结果图')
    plt.show()

# 二分K-均值聚类算法
def biKmeans(dataSet, k, distMeas=distEclud):
    m = shape(dataSet)[0]   # 获取样本数m
    clusterAssment = mat(zeros((m,2)))  #  初始化簇分配结果矩阵，第一列记录簇索引值，第二列存储误差
    centroid0 = mean(dataSet, axis=0).tolist()[0] # 初始化中心质点
    centList =[centroid0] #create a list with one centroid
    for j in range(m):  # 计算初始化误差
        clusterAssment[j,1] = distMeas(mat(centroid0), dataSet[j,:])**2
    while (len(centList) < k): # 该循环会不停对簇进行划分，直到得到想要的簇的数目为止
        lowestSSE = inf # 初始化最小SSE值为无穷大
        for i in range(len(centList)): # 遍历簇列表centList中的每一个簇
            ptsInCurrCluster = dataSet[nonzero(clusterAssment[:,0].A==i)[0],:]#get the data points currently in cluster i
            centroidMat, splitClustAss = kMeans(ptsInCurrCluster, 2, distMeas)  # 二分K-均值
            sseSplit = sum(splitClustAss[:,1])  # 计算第i簇划分后的SSE的值
            sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:,0].A!=i)[0],1])   # 计算第i簇以外的其他簇的SSE的值
            print ("sseSplit, and notSplit: ",sseSplit,sseNotSplit)
            if (sseSplit + sseNotSplit) < lowestSSE: # 如果新的划分得到的总的SSE值小于最小SSE值，则保存本次划分
                bestCentToSplit = i                  # 记录最佳划分簇 
                bestNewCents = centroidMat           # 记录按第i簇划分而得到的新的质心
                bestClustAss = splitClustAss.copy()  # 记录按第i簇划分而得到的新的划分误差
                lowestSSE = sseSplit + sseNotSplit   # 更新最小SSE值
        # 更新簇的分类结果，将新的质心添加到centList中，同时更新存储误差
        bestClustAss[nonzero(bestClustAss[:,0].A == 1)[0],0] = len(centList) #change 1 to 3,4, or whatever
        bestClustAss[nonzero(bestClustAss[:,0].A == 0)[0],0] = bestCentToSplit
        print ('the bestCentToSplit is: ',bestCentToSplit)
        print ('the len of bestClustAss is: ', len(bestClustAss))
        centList[bestCentToSplit] = bestNewCents[0,:].tolist()[0]#replace a centroid with two best centroids 
        centList.append(bestNewCents[1,:].tolist()[0])
        clusterAssment[nonzero(clusterAssment[:,0].A == bestCentToSplit)[0],:]= bestClustAss#reassign new clusters, and SSE
    return mat(centList), clusterAssment

import urllib
import json
def geoGrab(stAddress, city):
    apiStem = 'http://where.yahooapis.com/geocode?'  #create a dict and constants for the goecoder
    params = {}
    params['flags'] = 'J'#JSON return type
    params['appid'] = 'aaa0VN6k'
    params['location'] = '%s %s' % (stAddress, city)
    url_params = urllib.parse.urlencode(params)
    yahooApi = apiStem + url_params      #print url_params
    print (yahooApi)
    c=urllib.request.urlopen(yahooApi)
    return json.loads(c.read())

from time import sleep
def massPlaceFind(fileName):
    fw = open('places.txt', 'w')
    for line in open(fileName).readlines():
        line = line.strip()
        lineArr = line.split('\t')
        retDict = geoGrab(lineArr[1], lineArr[2])
        if retDict['ResultSet']['Error'] == 0:
            lat = float(retDict['ResultSet']['Results'][0]['latitude'])
            lng = float(retDict['ResultSet']['Results'][0]['longitude'])
            print ("%s\t%f\t%f" % (lineArr[0], lat, lng))
            fw.write('%s\t%f\t%f\n' % (line, lat, lng))
        else: print ("error fetching")
        sleep(1)
    fw.close()
    
def distSLC(vecA, vecB):#Spherical Law of Cosines
    a = sin(vecA[0,1]*pi/180) * sin(vecB[0,1]*pi/180)
    b = cos(vecA[0,1]*pi/180) * cos(vecB[0,1]*pi/180) * \
                      cos(pi * (vecB[0,0]-vecA[0,0]) /180)
    return arccos(a + b)*6371.0 #pi is imported with numpy

import matplotlib
import matplotlib.pyplot as plt
def clusterClubs(numClust=5):
    datList = []
    for line in open('places.txt').readlines():
        lineArr = line.split('\t')
        datList.append([float(lineArr[4]), float(lineArr[3])])
    datMat = mat(datList)
    myCentroids, clustAssing = biKmeans(datMat, numClust, distMeas=distSLC)
    fig = plt.figure()
    rect=[0.1,0.1,0.8,0.8]
    scatterMarkers=['s', 'o', '^', '8', 'p', \
                    'd', 'v', 'h', '>', '<']
    axprops = dict(xticks=[], yticks=[])
    ax0=fig.add_axes(rect, label='ax0', **axprops)
    imgP = plt.imread('Portland.png')
    ax0.imshow(imgP)
    ax1=fig.add_axes(rect, label='ax1', frameon=False)
    for i in range(numClust):
        ptsInCurrCluster = datMat[nonzero(clustAssing[:,0].A==i)[0],:]
        markerStyle = scatterMarkers[i % len(scatterMarkers)]
        ax1.scatter(ptsInCurrCluster[:,0].flatten().A[0], ptsInCurrCluster[:,1].flatten().A[0], marker=markerStyle, s=90)
    ax1.scatter(myCentroids[:,0].flatten().A[0], myCentroids[:,1].flatten().A[0], marker='+', s=300)
    plt.show()
